/*
 * Copyright (C) 2011-2012 Wojciech Dzierżanowski
 * See LICENSE.txt for licensing details.
 */

package wdzierzan.downstream.android;

import android.preference.*;
import wdzierzan.downstream.android.servermanager.Server;
import wdzierzan.downstream.android.servermanager.ServerManager;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;

/**
 * @author Wojciech Dzierżanowski (wojciech.dzierzanowski@gmail.com)
 */
public class ServerManagerActivity extends PreferenceActivity {

    private static final String EXTRA_SERVER_ID = "server-id";

    @Override
    protected void onStart() {
        super.onStart();
        initPreferenceScreen();
    }

    private void initPreferenceScreen() {
        PreferenceScreen screen = getPreferenceManager().createPreferenceScreen(this);
        setPreferenceScreen(screen);

        for (Server server : ServerManager.getInstance().getAllServers()) {

            Intent configIntent = new Intent(this, ServerConfigActivity.class);
            configIntent.putExtra(EXTRA_SERVER_ID, server.getId());

            PreferenceScreen serverPref = getPreferenceManager().createPreferenceScreen(this);
            serverPref.setTitle(server.getName());
            serverPref.setSummary(server.getUsername() + '@' + server.getHostname());
            serverPref.setIntent(configIntent);
            serverPref.setWidgetLayoutResource(R.layout.server_list_item_widget);
            screen.addPreference(serverPref);
        }

        Intent addIntent = new Intent(this, ServerConfigActivity.class);
        PreferenceScreen addServerPref = getPreferenceManager().createPreferenceScreen(this);
        addServerPref.setTitle(R.string.add_server);
        addServerPref.setIntent(addIntent);
        screen.addPreference(addServerPref);

        ListPreference formatPref = new ListPreference(this);
        formatPref.setTitle(R.string.audio_format);
        formatPref.setSummary(R.string.audio_format_summary);
        formatPref.setKey(ServerManager.PREFERENCE_FORMAT);
        formatPref.setEntries(Format.strings());
        formatPref.setEntryValues(Format.names());
        // This will give it a default value if we haven't stored the pref yet.
        formatPref.setValue(ServerManager.getInstance().getFormat().name());

        PreferenceCategory generalPrefs = new PreferenceCategory(this);
        generalPrefs.setTitle(R.string.general);
        screen.addPreference(generalPrefs);
        generalPrefs.addPreference(formatPref);
    }

    public void onRemoveClicked(View view) {
        Rect r = new Rect();
        ((LinearLayout) view.getParent().getParent()).getHitRect(r);
        final int index = getListView().pointToPosition(r.centerX(), r.centerY());
        new AlertDialog.Builder(ServerManagerActivity.this)
                .setTitle(R.string.ask_remove_title)
                .setMessage(R.string.ask_remove_message)
                .setPositiveButton(R.string.yes, new OnClickListener() {
                    public void onClick(DialogInterface di, int i) {
                            ServerManager.getInstance().removeServer(index);
                            initPreferenceScreen();
                        }
                    })
                .setNegativeButton(R.string.no, null)
                .create().show();
    }

    public static class ServerConfigActivity extends PreferenceActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.layout.server_preferences);
            adjustKeys();
        }

        @Override
        protected void onStop() {
            super.onStop();
            fetchDefaults();
        }

        private void adjustKeys() {
            int serverId = getIntent().getIntExtra(EXTRA_SERVER_ID, -1);
            if (serverId < 0)
                serverId = ServerManager.getInstance().createServer();

            PreferenceScreen prefs = getPreferenceScreen();

            for (int i = 0; i < prefs.getPreferenceCount(); i++) {

                EditTextPreference pref = (EditTextPreference) prefs.getPreference(i);

                String key = pref.getKey();
                key = ServerManager.getInstance().getPreferenceKey(key, serverId);
                pref.setKey(key);

                String value = prefs.getSharedPreferences().getString(key, null);
                if (value != null)
                    pref.setText(value);
            }
        }

        private void fetchDefaults() {
            int serverId = getIntent().getIntExtra(EXTRA_SERVER_ID, -1);
            assert serverId > 0;

            PreferenceScreen prefs = getPreferenceScreen();
            SharedPreferences.Editor editor = prefs.getSharedPreferences().edit();

            for (int i = 0; i < prefs.getPreferenceCount(); i++) {

                EditTextPreference pref = (EditTextPreference) prefs.getPreference(i);

                String value = prefs.getSharedPreferences().getString(pref.getKey(), null);
                if (value == null) {
                    value = pref.getText();
                    editor.putString(pref.getKey(), value);
                }
            }

            editor.commit();
        }
    }
}
